<?php

namespace App\Service\Admin;

use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use App\Utils\MD5Token;

class LoginService
{
    #[Inject]
    protected MD5Token $md5Token;

    /**
     * Notes:登录逻辑
     * 2025/6/7
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $ip ip
     * @return array
     * @throws \Exception
     */
    public function login(string $username, string $password, string $ip): array
    {
        $administrator = \App\Model\Administrator::query()
            ->where("username",$username)
            ->where('status', '!=', \App\Model\Administrator::FORBID_STATUS)
            ->first();
        if (!$administrator) {
            throw new \Exception('用户不存在或禁用', \App\Constants\ErrorCode::USER_NOT_EXIST_OR_FORBID);
        }
        if (! password_verify($password, $administrator->password)) {
            throw new \Exception('账号或者密码错误', \App\Constants\ErrorCode::USER_PASSWORD_ERROR);
        }
        // 更新登录时间
        $administrator->login_at = Carbon::now()->format('Y-m-d H:i:s');
        $administrator->ip = $ip;
        $administrator->save();
        $token = $this->md5Token->generateToken($administrator->id,$administrator->toArray());
        return [
            'token' => $token,
            'user' => $administrator,
        ];
    }
}